import * as vscode from 'vscode';
import { MCPServer, ViewItemContextValue } from './models';
import { ApiService } from './api';
import * as path from 'path';

export class MCPServerTreeItem extends vscode.TreeItem {
  constructor(
    public readonly server: MCPServer,
    public readonly contextValue: string,
    public readonly command?: vscode.Command
  ) {
    super(server.name, vscode.TreeItemCollapsibleState.None);
    
    if (server.id === 'empty') {
      this.description = server.description;
      this.tooltip = new vscode.MarkdownString(server.description);
      return;
    }
    
    // 创建丰富的工具提示
    const tooltip = new vscode.MarkdownString();
    tooltip.isTrusted = true;
    tooltip.appendMarkdown(`## ${server.name} ${server.version ? `v${server.version}` : ''}\n\n`);
    tooltip.appendMarkdown(`${server.description}\n\n`);
    
    // 添加标签信息
    const tooltipTags = [];
    if (server.isInternal) {
      tooltipTags.push('📦 内部');
    }
    if (server.language) {
      tooltipTags.push(`🔧 ${server.language}`);
    }
    if (server.authType) {
      tooltipTags.push(`🔒 ${server.authType}`);
    }
    
    if (tooltipTags.length > 0) {
      tooltip.appendMarkdown(`**标签:** ${tooltipTags.join(' | ')}\n\n`);
    }
    
    if (server.author) {
      tooltip.appendMarkdown(`**作者:** ${server.author}\n\n`);
    }
    
    if (server.github) {
      tooltip.appendMarkdown(`**GitHub:** ${server.github}\n\n`);
    }
    
    if (server.installed) {
      tooltip.appendMarkdown(`$(check) **已安装**`);
    }
    
    this.tooltip = tooltip;
    
    // 添加彩色标签
    let tags = '';
    if (server.isInternal) {
      tags += '$(organization) 内部 ';
    }
    if (server.language) {
      tags += `$(code) ${server.language} `;
    }
    
    // 在树视图中显示简短描述
    let shortDescription = server.description;
    if (shortDescription.length > 50) {
      shortDescription = shortDescription.substring(0, 50) + '...';
    }
    
    // 设置标签和描述，不使用MarkdownString
    this.label = server.name;
    this.description = tags + shortDescription + (server.installed ? ' $(check) 已安装' : '');
    
    // 自定义图标
    if (server.installed) {
      this.iconPath = new vscode.ThemeIcon('verified');
    } else if (server.isInternal) {
      this.iconPath = new vscode.ThemeIcon('organization');
    } else {
      this.iconPath = new vscode.ThemeIcon('package');
    }
  }
}

export class MCPServerTreeProvider implements vscode.TreeDataProvider<MCPServerTreeItem> {
  private _onDidChangeTreeData: vscode.EventEmitter<MCPServerTreeItem | undefined | null | void> = new vscode.EventEmitter<MCPServerTreeItem | undefined | null | void>();
  readonly onDidChangeTreeData: vscode.Event<MCPServerTreeItem | undefined | null | void> = this._onDidChangeTreeData.event;
  
  private servers: MCPServer[] = [];
  private searchQuery: string = '';
  private filter: string = 'all';
  private sortOrder: string = 'name';

  constructor(private apiService: ApiService) {}

  refresh(): void {
    this._onDidChangeTreeData.fire();
  }

  updateSearchQuery(query: string): void {
    this.searchQuery = query;
    this.refresh();
  }
  
  // 新增筛选功能
  updateFilter(filter: string): void {
    this.filter = filter;
    this.refresh();
  }
  
  // 新增排序功能
  updateSortOrder(sortOrder: string): void {
    this.sortOrder = sortOrder;
    this.refresh();
  }

  getTreeItem(element: MCPServerTreeItem): vscode.TreeItem {
    return element;
  }

  async getChildren(element?: MCPServerTreeItem): Promise<MCPServerTreeItem[]> {
    if (element) {
      return [];
    }

    try {
      const response = await this.apiService.getMCPServerList(1, 100, this.searchQuery);
      this.servers = response.servers;
      
      // 如果没有搜索结果，显示提示
      if (this.servers.length === 0 && this.searchQuery) {
        return [new MCPServerTreeItem(
          {
            id: 'empty',
            name: `没有找到 "${this.searchQuery}" 相关的 MCP Server`,
            description: '请尝试其他关键词',
            version: '',
            author: '',
            github: '',
            isInternal: false
          },
          'empty'
        )];
      }
      
      // 应用筛选
      let filteredServers = [...this.servers];
      
      if (this.filter !== 'all') {
        switch (this.filter) {
          case 'internal':
            filteredServers = filteredServers.filter(server => server.isInternal);
            break;
          case 'opensource':
            filteredServers = filteredServers.filter(server => !server.isInternal);
            break;
          case 'python':
            filteredServers = filteredServers.filter(server => 
              server.language?.toLowerCase() === 'python');
            break;
          case 'javascript':
            filteredServers = filteredServers.filter(server => 
              server.language?.toLowerCase() === 'javascript' || 
              server.language?.toLowerCase() === 'js');
            break;
          case 'java':
            filteredServers = filteredServers.filter(server => 
              server.language?.toLowerCase() === 'java');
            break;
        }
      }
      
      // 如果筛选后没有结果，显示提示
      if (filteredServers.length === 0) {
        return [new MCPServerTreeItem(
          {
            id: 'empty',
            name: `没有符合筛选条件的 MCP Server`,
            description: '请尝试其他筛选条件',
            version: '',
            author: '',
            github: '',
            isInternal: false
          },
          'empty'
        )];
      }
      
      // 应用排序
      switch (this.sortOrder) {
        case 'name':
          filteredServers.sort((a, b) => a.name.localeCompare(b.name));
          break;
        case 'installs':
          // 模拟安装量排序，实际上应该从API获取安装量数据
          filteredServers.sort((a, b) => (b.installed ? 1 : 0) - (a.installed ? 1 : 0));
          break;
        case 'updated':
          // 模拟更新时间排序，实际上应该从API获取更新时间数据
          // 这里简单地按照版本号排序
          filteredServers.sort((a, b) => {
            const versionA = a.version || '0.0.0';
            const versionB = b.version || '0.0.0';
            return versionB.localeCompare(versionA);
          });
          break;
      }
      
      // 为每个服务器创建一个树项，使用卡片式布局
      return filteredServers.map(server => {
        return new MCPServerTreeItem(
          server,
          server.installed ? ViewItemContextValue.INSTALLED_SERVER : ViewItemContextValue.SERVER,
          {
            command: 'mcphub.openServerDetails',
            title: '查看详情',
            arguments: [server]
          }
        );
      });
    } catch (error) {
      vscode.window.showErrorMessage('无法加载MCP Server 列表');
      return [new MCPServerTreeItem(
        {
          id: 'empty',
          name: '加载失败',
          description: '无法连接到服务器，请检查网络连接或稍后再试',
          version: '',
          author: '',
          github: '',
          isInternal: false
        },
        'empty'
      )];
    }
  }
}

export class InstalledMCPServerTreeProvider implements vscode.TreeDataProvider<MCPServerTreeItem> {
  private _onDidChangeTreeData: vscode.EventEmitter<MCPServerTreeItem | undefined | null | void> = new vscode.EventEmitter<MCPServerTreeItem | undefined | null | void>();
  readonly onDidChangeTreeData: vscode.Event<MCPServerTreeItem | undefined | null | void> = this._onDidChangeTreeData.event;
  
  private servers: MCPServer[] = [];
  private sortOrder: string = 'name';

  constructor(private apiService: ApiService) {}

  refresh(): void {
    this._onDidChangeTreeData.fire();
  }
  
  // 新增排序功能
  updateSortOrder(sortOrder: string): void {
    this.sortOrder = sortOrder;
    this.refresh();
  }

  getTreeItem(element: MCPServerTreeItem): vscode.TreeItem {
    return element;
  }

  async getChildren(element?: MCPServerTreeItem): Promise<MCPServerTreeItem[]> {
    if (element) {
      return [];
    }

    try {
      this.servers = await this.apiService.getInstalledMCPServers();
      
      if (this.servers.length === 0) {
        return [new MCPServerTreeItem(
          {
            id: 'empty',
            name: '没有已安装的MCP Server',
            description: '点击安装按钮来安装MCP Server',
            version: '',
            author: '',
            github: '',
            isInternal: false
          },
          'empty'
        )];
      }
      
      // 应用排序
      let sortedServers = [...this.servers];
      
      switch (this.sortOrder) {
        case 'name':
          sortedServers.sort((a, b) => a.name.localeCompare(b.name));
          break;
        case 'updated':
          // 模拟更新时间排序，按版本号排序
          sortedServers.sort((a, b) => {
            const versionA = a.version || '0.0.0';
            const versionB = b.version || '0.0.0';
            return versionB.localeCompare(versionA);
          });
          break;
      }
      
      // 为每个已安装的服务器创建一个树项，使用卡片式布局
      return sortedServers.map(server => {
        return new MCPServerTreeItem(
          server,
          ViewItemContextValue.INSTALLED_SERVER,
          {
            command: 'mcphub.openServerDetails',
            title: '查看详情',
            arguments: [server]
          }
        );
      });
    } catch (error) {
      vscode.window.showErrorMessage('无法加载已安装的MCP Server 列表');
      return [new MCPServerTreeItem(
        {
          id: 'empty',
          name: '加载失败',
          description: '无法获取已安装的MCP Server列表',
          version: '',
          author: '',
          github: '',
          isInternal: false
        },
        'empty'
      )];
    }
  }
} 